package models;

import helpers.GeneralHelper;
import helpers.SettingHelper;

import java.util.ArrayList;
import java.util.List;

import javax.cache.Cache;

import com.google.appengine.api.NamespaceManager;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

import entities.Application;

public class ApplicationModel {
	private Objectify ofy;
	
	private Cache cache = null;
	
	private String cachePrefix = "application_";
	
	private static ApplicationModel instance = null;
	
	public static ApplicationModel getInstance() {
		if (instance == null) {
			instance = new ApplicationModel();
		}
		
		return instance;
	}
	
	private ApplicationModel() {
		try {
			ObjectifyService.register(Application.class);
		} catch (Exception e) {
			//e.printStackTrace();
		}
		
		cache = GeneralHelper.getCache();
		ofy = GeneralHelper.getObjectify();
	}
	
	public List<Application> list(int page, int limit) {
		NamespaceManager.set(SettingHelper.getGeneralNamespace());
		
		List<Application> apps = new ArrayList<Application>();
		Application app = new Application();
		
		String cacheName = cachePrefix + "list_page_" + page + "_limit_" + limit;
		boolean isCached = false;
		
		if (cache != null) {
			try {
				apps = (List<Application>) cache.get(cacheName);
				if (apps != null) isCached = true;
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		
		if (!isCached) {
			int start = (page - 1) * limit;
			apps = ofy.query(Application.class).limit(limit).offset(start).list();
			
			if (cache != null && apps != null) {
				try {
					cache.put(cacheName, apps);
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}
		
		return apps;
	}
	
	public List<Application> getAll() {
		List<Application> apps = new ArrayList<Application>();
		
		String cacheName = cachePrefix + "_list_all";
		boolean isCached = false;
		
		if (cache != null) {
			try {
				apps = (List<Application>) cache.get(cacheName);
				if (apps != null) isCached = true;
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
		
		if (!isCached) {
			apps = ofy.query(Application.class).list();
			
			if (cache != null && apps != null) {
				try {
					cache.put(cacheName, apps);
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
		}
		
		return apps;
	}
	
	public Application get(String id) {
		NamespaceManager.set(SettingHelper.getGeneralNamespace());
		
		Application app = new Application();
		
		try {
			app = ofy.get(new Key<Application>(Application.class, id));
		} catch (Exception e) {
			app = null;
		}
		
		return app;
	}
	
	public boolean checkExists(String id) {
		boolean exists = false;
		
		Application app = get(id);
		
		if (app != null) {
			exists = true;
		}
		
		return exists;
	}
}
